/*
 * 蓝牙API封装
 */
var app=getApp()
// 封装打开蓝牙适配器接口
export function openBlue(isFirestShow) {
  return new Promise((resolved, rejected) => {
    wx.closeBluetoothAdapter({
      success: function (r) {
        wx.openBluetoothAdapter({ //调用微信小程序api 打开蓝牙适配器接口
          success: function (res) {
            resolved('success')
          },
          fail: function (res) { //如果手机上的蓝牙没有打开，可以提醒用户
            rejected('fail')
            wx.showModal({
              title: '提示',
              content: '请检查手机蓝牙是否打开',
              showCancel: false})
          }
        })
      },
      fail: err => {
        if (isFirestShow) {
          warning("该设备不支持蓝牙")
        }
        rejected('noBlue')
      }
    });
  })
}

// 蓝牙写入数据
export const writeBLECharacteristicValue = (deviceId, serviceId, writeCharacteristicId, value) => {
  return new Promise((resolve, reject) => {
    console.log("发送数据", value);
    wx.writeBLECharacteristicValue({
      deviceId: deviceId,
      serviceId: serviceId,
      characteristicId: writeCharacteristicId,
      value: value,
      // 发送数据成功得回调
      success: (result) => {
        wx.vibrateShort({
          type: 'high',
        })
        resolve(result);
      },
      // 发送数据失败的回调
      fail: (err) => {
        // console.log(1);
        // reject(err);
        console.log(err);
      },
      complete:()=>{
        app.globalData.isActive=""
      }
    })
  })
}
//2.查看蓝牙适配器状态
export const getBluetoothAdapterState = () => {
  return new Promise((resolve, reject) => {
    wx.getBluetoothAdapterState({
      success: (result) => {
        resolve(result);
      },
      fail: (err) => {
        wx.showToast({
          title: '请打开蓝牙',
          icon: 'none'
        })
        reject(err);
      }
    }) 
  })
}
//3.搜索设备
export const startBluetoothDevicesDiscovery = () => {
  return new Promise((resolve, reject) => {
    wx.startBluetoothDevicesDiscovery({
      allowDuplicatesKey: false,
      services:[],
      powerLevel:'high',
      success: (result) => {
        resolve(result);
      },
      fail: (err) => {
        console.log('error',err);
        if(err.errCode==10000){
          wx.showToast({
            title: '请打开定位',
            icon:'error'
          })
        }else{
          wx.showToast({
            title: '搜索设备失败',
            icon: 'none'
          })
        }

        reject(err);
      }
    })
  })
}
//4.获取蓝牙设备信息
export const getBluetoothDevices = () => {
  return new Promise((resolve, reject) => {
    wx.getBluetoothDevices({
      success: (result) => {
        resolve(result);
      },
      fail: (err) => {
        wx.showToast({
          title: '未获取到设备信息',
          icon: 'none'
        })
        reject(err);
      }
    })
  })
}
//5.连接设备
export const CcreateBLEConnection = (deviceId,name="") => {
  console.log('name', name);
  console.log('id', deviceId);
  wx.showLoading({
    title: "连接蓝牙设备中...."
  })
  return new Promise((resolve, reject) => {
    wx.createBLEConnection({
      deviceId: deviceId,
      timeout:10000,
      success: (result) => {
        resolve(result);
      },
      fail: (err) => {
        wx.showToast({
          title: '未连接到蓝牙，可能是设备没通电',
          icon: 'none'
        })
        reject(err);
      },
      complete:()=>{
        wx.hideLoading()
      }
    })
  })
}
//6.停止扫描设备
export const CstopBluetoothDevicesDiscovery = () => {
  return new Promise((resolve, reject) => {
    wx.stopBluetoothDevicesDiscovery({
      success: (result) => {
        resolve(result);
      },
      fail: (err) => {
        reject(err);
      }
    })
  })
}
//7.获取连接设备的service服务
export const getBLEDeviceServices = (deviceId) => {
  return new Promise((resolve, reject) => {
    wx.getBLEDeviceServices({
      deviceId: deviceId,
      success: (result) => {
        console.log("成功")
        resolve(result);
      },
      fail: (err) => {
        wx.showToast({
          title: '未能获取服务',
        })
        reject(err);
      }
    })
  })
}
//8.获取连接设备具有读写功能服务的所有特征值
export const getBLEDeviceCharacteristics = (deviceId, serviceId) => {
  return new Promise((resolve, reject) => {
    wx.getBLEDeviceCharacteristics({
      deviceId: deviceId,
      serviceId: serviceId,
      success: (result) => {
        resolve(result);
      },
      fail: (err) => {
        reject(err);
      }
    })
  })
}
//9.启动蓝牙设备特征值变化
export const notifyBLECharacteristicValueChange = (deviceId, serviceId, notifyCharacteristicId) => {
  return new Promise((resolve, reject) => {
    wx.notifyBLECharacteristicValueChange({
      deviceId: deviceId,
      serviceId: serviceId,
      characteristicId: notifyCharacteristicId,
      state: true,
      success: (result) => {
        console.log(result);
        resolve(result);
      },
      fail: (err) => {
        reject(err);
      }
    })
  })
}
//12.关闭蓝牙
export const closeBluetoothAdapter = () => {
  return new Promise((resolve, reject) => {
    wx.closeBluetoothAdapter({
      success: (result) => {
        resolve(result);
      },
      fail: (err) => {
        wx.showToast({
          title: '数据发送成功，但未关闭蓝牙，请手动关闭',
          icon: 'none'
        })
        reject(err);
      }
    })
  })
}
// export const onBluetoothAdapterStateChange=function(res){
//   return new Promise(resolve,reject){

//   }
// }